package com.example.hellonotes.fragment;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.example.hellonotes.BaseFragment;
import com.example.hellonotes.R;
import com.example.hellonotes.adapter.NotesBmobAdapter;
import com.example.hellonotes.entity.Person2;
import com.example.hellonotes.utils.TitleBuilder;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;

public class HomeFragment extends BaseFragment{

	private View view;
	private NotesBmobAdapter notesBmobAdapter;
	private ArrayList<Person2> mListItems;
	private TextView networkTips;
	private ProgressBar progressbar;
	private int pageNum;
	private boolean pullFromUser;
	private String lastItemTime;
	//listView - 下拉刷新控件
	private PullToRefreshListView plv_status_detail;
	public enum RefreshType{
		REFRESH,LOAD_MORE
	}
	private RefreshType mRefreshType = RefreshType.LOAD_MORE;
	//private TextView tv;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		initView();
		//initListView();	
		return view;
	}
	
	private void initView() {
		view = View.inflate(activity, R.layout.frag_home, null);
		new TitleBuilder(view).setTitleText("首页");
		pageNum = 0;
		mListItems = new ArrayList<Person2>();
		networkTips = (TextView)view.findViewById(R.id.networkTips);
		progressbar = (ProgressBar)view.findViewById(R.id.progressBar);
		plv_status_detail = (PullToRefreshListView)view.findViewById(R.id.plv_status_detail);
		notesBmobAdapter = new NotesBmobAdapter(activity, mListItems);
		plv_status_detail.setAdapter(notesBmobAdapter);
		plv_status_detail.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO 自动生成的方法存根
			/*	String label = DateUtils.formatDateTime(activity, System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
				//设置下拉刷新时 的 提示信息
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				plv_status_detail.setMode(Mode.BOTH);
				pullFromUser = true;
				mRefreshType = RefreshType.REFRESH;
				pageNum = 0;
				lastItemTime = getCurrentTime();*/
				selectDB();
			}
		});
		
	}
	
	
	/**
	 * 获取数据
	 */
	public void selectDB() {
		setState(LOADING);
		//获取查询对象
		BmobQuery<Person2> query = new BmobQuery<Person2>();
		//已创建时间排序
		query.order("-createdAt");
		//设置查询返回的数据条数（10）
		query.setLimit(10);
		//获取当前系统的时间
		BmobDate date = new BmobDate(new Date(System.currentTimeMillis()));
		//查询创建时间 小于当前系统时间的所有数据
		query.addWhereLessThan("createdAt", date);
		//忽略前XX条数据（即第一页数据结果） 这是分页显示相关的设置
		//每次查询都忽略前面已查询过的数据
		query.setSkip(10*(pageNum++));
		// 希望在查询帖子信息的同时也把发布人的信息查询出来
		query.include("user");
		query.findObjects(activity, new FindListener<Person2>() {
			
			@Override
			public void onSuccess(List<Person2> list) {
				// TODO 自动生成的方法存根
				if(list.size()!=0&&list.get(list.size()-1)!=null){
					if(mRefreshType==RefreshType.REFRESH){
						mListItems.clear();
					}
					if(list.size()<10){
					}
					/*if(MyApplication.getInstance().getCurrentUser()!=null){
						list = DatabaseUtil.getInstance(mContext).setFav(list);
					}*/
					mListItems.addAll(list);
					notesBmobAdapter.notifyDataSetChanged();
					setState(LOADING_COMPLETED);
					plv_status_detail.onRefreshComplete();
				}else{
					//ActivityUtil.show(getActivity(), "暂无更多数据~");
					pageNum--;
					setState(LOADING_COMPLETED);
					plv_status_detail.onRefreshComplete();
				}	
			}
			@Override
			public void onError(int arg0, String msg) {
				// TODO 自动生成的方法存根
				System.out.println("数据查询失败"+msg);
			}
		});
		plv_status_detail.setAdapter(notesBmobAdapter);
	}
	
	/**
	 * 下拉刷新控件相关 pulltorefresh
	 *//*
	private void initListView() {
		// listView - 下拉刷新控件
		plv_status_detail = (PullToRefreshListView)view.findViewById(R.id.plv_status_detail);
		notesBmobAdapter = new NotesBmobAdapter(activity, mListItems);
		plv_status_detail.setAdapter(notesBmobAdapter);
		final ListView lv = plv_status_detail.getRefreshableView();
		// 下拉刷新监听
		plv_status_detail.setMode(Mode.BOTH);
		plv_status_detail.setOnRefreshListener(new OnRefreshListener2<ListView>() {
			
			*//**
			 * 下拉刷新
			 *//*
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO 自动生成的方法存根
				//把当前的系统时间 转换成 2月24日 下午12:57 这样的字符串
				String label = DateUtils.formatDateTime(activity, System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
				//设置下拉刷新时 的 提示信息
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				plv_status_detail.setMode(Mode.BOTH);
				pullFromUser = true;
				mRefreshType = RefreshType.REFRESH;
				pageNum = 0;
				lastItemTime = getCurrentTime();
				selectDB();
			}
			
			
			*//**
			 * 上啦刷新
			 *//*
			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO 自动生成的方法存根
				mRefreshType = RefreshType.LOAD_MORE;
				selectDB();
			}
		});
		
		
		
		// 滑动到底部最后一个item监听
		plv_status_detail.setOnLastItemVisibleListener(
				new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						//selectDB();
					}
				});
		
		
		// 滚动状态监听
		plv_status_detail.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// 0-pullHead 1-detailHead 2-tab
				// 如果滑动到tab为第一个item时,则显示顶部隐藏的shadow_tab,作为悬浮菜单栏
				shadow_status_detail_tab.setVisibility(firstVisibleItem >= 2 ?
						View.VISIBLE : View.GONE);
			}
		});
	}*/
	

	private static final int LOADING = 1;
	private static final int LOADING_COMPLETED = 2;
	private static final int LOADING_FAILED =3;
	private static final int NORMAL = 4;
	public void setState(int state){
		switch (state) {
		case LOADING:
			if(mListItems.size() == 0){
				plv_status_detail.setVisibility(View.GONE);
				progressbar.setVisibility(View.VISIBLE);
			}
			networkTips.setVisibility(View.GONE);
			
			break;
		case LOADING_COMPLETED:
			networkTips.setVisibility(View.GONE);
			progressbar.setVisibility(View.GONE);
			
			plv_status_detail.setVisibility(View.VISIBLE);
			plv_status_detail.setMode(Mode.BOTH);

			
			break;
		case LOADING_FAILED:
			if(mListItems.size()==0){
				plv_status_detail.setVisibility(View.VISIBLE);
				plv_status_detail.setMode(Mode.PULL_FROM_START);
				networkTips.setVisibility(View.VISIBLE);
			}
			progressbar.setVisibility(View.GONE);
			break;
		case NORMAL:
			
			break;
		default:
			break;
		}
	}
	
	/**
	 *获取本地时间 
	 */
	private String getCurrentTime(){
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	     String times = formatter.format(new Date(System.currentTimeMillis()));
	     return times;
	}
	
}
